package com.shanghaionstar.activity.webview.handler.picture;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/6/8. 通用WebView 的Setting设置
 *
 * @author xuff 2016年6月8日15:55:35
 */

public class CommonWebSetting {


    public static void initSetting(final WebView mWebView, final ProgressBar mProgressBar, final Context context) {
        initSetting(mWebView, mProgressBar, context, null);
    }

    public static void initSetting(final WebView mWebView, final ProgressBar mProgressBar, final Context context, final TextView titleTextView) {

        WebSettings webSettings = mWebView.getSettings();


        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSettings.setJavaScriptEnabled(true); // 启用JS脚本
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setBuiltInZoomControls(true); // 启用内置缩放装置

        // 打开页面时， 自适应屏幕：
        webSettings.setUseWideViewPort(true);// 设置概览模式
        webSettings.setLoadWithOverviewMode(true);//


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }

//        //如果webView中需要用户手动输入用户名、密码或其他，则webview必须设置支持获取手势焦点。
        mWebView.requestFocusFromTouch();

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                // context.startActivity(intent);
                DownloadManager downloadManager;
                downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request downloadManagerRequest = new DownloadManager.Request(uri);
                downloadManagerRequest.setMimeType(mimetype);
                String fileName = System.currentTimeMillis() + "."
                        + contentDisposition.substring(contentDisposition.lastIndexOf("."));
                downloadManagerRequest.setDestinationInExternalPublicDir(FileUtils.DOWNLOAD, fileName);
                downloadManagerRequest.setDescription(contentDisposition);
                downloadManagerRequest.setVisibleInDownloadsUi(true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    downloadManagerRequest.allowScanningByMediaScanner();
                    downloadManagerRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);

                }
                long reference = downloadManager.enqueue(downloadManagerRequest);
                // 把当前下载的ID保存起来
                SharedPrefsHelp.getInstance().setSharedPrefs("downloadplato", reference);
            }
        });

        // WebViewClient用来处理WebView各种通知、请求事件等,重写里面的方法即可
        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // handler.cancel(); 默认的处理方式，WebView变成空白页
                handler.proceed();
                view.reload();
                // handleMessage(Message msg); 其他处理
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("tel"))
                {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    context.startActivity(intent);

                }
                else
                {
                    view.loadUrl(url);
                }
                return true;
            }

        });

        // WebChromeClienty用来处理WebView的Javascript的对话框、网站图标、网站title、加载进度等,重写里面的方法即可
        mWebView.setWebChromeClient(new WebChromeClient() {
            // 当WebView进度改变时更新窗口进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // Activity的进度范围在0到10000之间,所以这里要乘以100
                if (mProgressBar != null) {
                    if (newProgress == 100 && mProgressBar.getVisibility() == View.VISIBLE) {
                        mProgressBar.setVisibility(View.GONE);
                    } else {
                        if (mProgressBar.getVisibility() != View.VISIBLE) {
                            mProgressBar.setVisibility(View.VISIBLE);
                        }
                        mProgressBar.setProgress(newProgress);
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (titleTextView != null)
                    titleTextView.setText(title);
            }
        });

        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                        mWebView.goBack(); // 后退
                        return true; // 已处理
                    }
                }
                return false;
            }
        });

    }

}
